import Vue from "vue"
import Vuex from "vuex"

import {
	SetLoginToken,
	GetLoginToken,
	RemoveLoginToken,
	SetUserInfo,
	GetUserInfo,
	SetLocation,
	GetLocation,

} from '../utils/auth.js'

import http from '@/utils/http'

Vue.use(Vuex)
const token = GetLoginToken();
const userInfo = GetUserInfo();
const location = GetLocation();

export default new Vuex.Store({
	state: {
		token: token,
		userInfo: userInfo,
		userId: null,
		vistorSelectList: [],
		location: location,
		footerBarList: [{
				url: "/pages/index/index",
				label: "考 勤",
			},			
			{
				url: "/pages/user-center/user-center",
				label: "个人信息",
				src: "cuIcon-myfill"
			}
		]
	},
	getters: { //get方法
		token: state => state.token,
		footerBarList: state => state.footerBarList,
		userInfo: state => state.userInfo,
		userId: state => state.userId,
		location: state => state.location,
	},
	mutations: { //set方法
		SET_TOKEN: (state, token) => {
			state.token = token;
		},
		SET_USERINFO: (state, userInfo) => {
			state.userInfo = userInfo;
			if (userInfo) {
				state.userId = userInfo.Id;

			} else {
				state.userId = null;

			}
		},

		SET_LOCATION: (state, location) => {
			state.location = location;
		},
	},
	actions: {
		async SyncLocation({
			commit
		}, location) {
			console.log("同步结果",location)
			commit("SET_LOCATION", location);
			SetLocation(location);
		},

		/**
		 * 用户登录方法
		 */
		async Userlogin({
			commit
		}, loginForm) {
			const {
				UserName,
				Password,
				RoleType,
				WxCode
			} = loginForm;
			let {
				Data,
				Success,
				Msg
			} = await http.PostAsync("/User/SignIn", {
				UserName: UserName,
				Password: Password,
				RoleType: RoleType,
				WxCode:WxCode,
			})

			if (Data) {

				commit("SET_TOKEN", Data);
				SetLoginToken(Data);
			}

			return {
				Data,
				Success,
				Msg
			};
		},
		/**
		 * 用户退出
		 */
		async LoginOut({
			commit
		}) {
			commit("SET_TOKEN", "");
			commit("SET_USERINFO", null);
			RemoveLoginToken();
		},
		async TokenLose({
			commit
		}) {
			commit("SET_TOKEN", "");
			commit("SET_USERINFO", null);
			RemoveLoginToken();
			uni.navigateTo({
				url: "/pages/login/login"
			})

		},
		/**
		 * 获取用户信息
		 */
		async UserInfoByToken({
			commit,
			state
		}, userInfo) {
			if (state.token) {
				var {
					Data,
					Success,
					Msg
				} = await http.PostAsync("/User/GetByToken", {})
				if (Data.Id == null) {
					commit("SET_TOKEN", "");
					commit("SET_USERINFO", null);
					RemoveLoginToken();
					// uni.navigateTo({
					// 	url: "/pages/login/login"
					// })
					return Data;
				}
				commit("SET_USERINFO", Data);
				SetUserInfo(Data);
			}
			return Data;
		},

	},
})